<?php
	include_once('dbcon.php');
	include_once('constants.php');
	include_once('error_log_db.php');
	include_once('update_user_points_db.php');
	include_once('general_functions_db.php');

	function checkValidEditCategory($category_id, $user_id) {
		global $mysqli;

		$category_query = $mysqli->query("SELECT name, user_id, creation_date FROM categories WHERE category_id=".$category_id);
		logIfError($mysqli, $user_id , "upload_category_db", "checkValidEditCategory", "1");
		$category = $category_query->fetch_assoc();

		if (time() - strtotime($category['creation_date']) > CATEGORY_MAX_EDIT_TIME + SERVER_SIDE_EXTRA_WAIT_TIME) {
			logMsg($user_id, "EDIT CATEGORY INVALID TIME. category_id=".$category_id.". name=".$category['name']);
			return false;
		}

		if ($category['user_id'] != $user_id) {
			logMsg($user_id, "EDIT CATEGORY INVALID USER. category_id=".$category_id.". Owner_user=".$category['user_id']." Fake_user=".$user_id);
			return;
		}

		return true;
	}

	if(isset($_REQUEST['user_id']) && isset($_REQUEST['name']) && isset($_REQUEST['first_name']) && isset($_REQUEST['last_name'])) {
		
		$user_id = adaptToSql($_REQUEST['user_id']);
		$name = adaptToSql($_REQUEST['name']);
		$first_name = adaptToSql($_REQUEST['first_name']);
		$last_name = adaptToSql($_REQUEST['last_name']);

		if (isset($_REQUEST['category_id'])) {
			if (checkValidEditCategory($_REQUEST['category_id'], $user_id ) == false) {
				echo $_REQUEST['category_id'];
				return;
			}

			$mysqli->query("UPDATE categories SET name=\"".$name."\" WHERE category_id=".$_REQUEST['category_id']);
		} else {
			$mysqli->query("INSERT INTO categories (user_id, first_name, last_name, name, likes, dislikes, score, creation_date) VALUES('".$user_id ."',\"".$first_name."\",\"".$last_name."\",\"".$name."\",'0','0','0','".date('Y-m-d H:i:s')."')");
		}

		logIfError($mysqli, $user_id , "upload_category_db", "", "1");
	
		$action = null;
		$category_id = null;
		if (isset($_REQUEST['category_id'])) {
			$action = "Category edited.";
			$category_id = $_REQUEST['category_id'];
		} else {
			$action = "Category created.";
			// Get the last category created by the user
			$category_query = $mysqli->query("SELECT * FROM categories WHERE user_id=".$user_id ." ORDER BY category_id DESC LIMIT 1");
			logIfError($mysqli, $user_id , "upload_category_db", "", "1");
			
			$category = $category_query->fetch_assoc();
			
			$category_id = $category['category_id'];
		}

		logMsg($user_id , $action." CategoryId=".$category_id.". Name=".$name);
		echo $category_id;
	}
?>
